package com.qilu.pe.ui.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Global;
import com.qilu.pe.base.MyApp;
import com.qilu.pe.dao.bean.Doctor;
import com.qilu.pe.dao.bean.EventModel;
import com.qilu.pe.dao.bean.Score;
import com.qilu.pe.dao.bean.SettingsData;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.ActiviceCollector;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.support.util.PeUtil;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 我的积分
public class MyScoreActivity extends Base2Activity implements OnRefreshListener, OnLoadMoreListener {
    private RecyclerView rcv_list;// 积分列表
    private ImageView ivScoreRule;//积分规则
    private TextView tvTotalScore;//总积分
    private MyScoreListAdapter adapter;
    private List<Score> scoreList = new ArrayList<>();
    private String scoreRule="";//积分规则

    private SmartRefreshLayout vRefresh;
    private int mPage = 1, mPageSize = 15;
    @Override
    protected int getLayoutRes() {
        return R.layout.activity_my_score;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        rcv_list = findViewById(R.id.rcv_list);
        vRefresh = findViewById(R.id.vRefresh);
        setHeadTitle("我的积分");

        LinearLayoutManager manager = new LinearLayoutManager(this);
        adapter = new MyScoreListAdapter(this);
        rcv_list.setLayoutManager(manager);
        rcv_list.setAdapter(adapter);
        ivScoreRule=findViewById(R.id.iv_score_rule);
        tvTotalScore=findViewById(R.id.tv_total_score);
        vRefresh.setOnRefreshListener(this);
        vRefresh.setOnLoadMoreListener(this);
        vRefresh.autoRefresh();
        rxList.add(reqDataList());
        ivScoreRule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logg.e("积分规则=="+scoreRule);

                AlertDialog.Builder builder = new AlertDialog.Builder(MyScoreActivity.this);
                builder.setTitle("积分规则");
                builder.setMessage(scoreRule);//内容
                AlertDialog dialog=builder.create();
                builder.setCancelable(true);
//                        .create();
                Window dialogWindow = dialog.getWindow();
                WindowManager.LayoutParams lp =dialogWindow.getAttributes();
//                wlp.gravity = Gravity.TOP | Gravity.RIGHT;
                dialogWindow.setGravity(Gravity.RIGHT | Gravity.TOP);
                //显示的坐标
//                lp.x = 300;
//                lp.y = 150;
                dialog.show();
                dialogWindow.setLayout(600,800);
            }
        });
        APIRetrofit.getDefault().getSettings(Global.HEADER)
                .compose(RxUtil.<BaseResult2<List<SettingsData>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<SettingsData>>>() {
                    @Override
                    public void accept(BaseResult2<List<SettingsData>> res) throws Exception {
                        if (res.isSuccess()) {
                            if (res.getData() != null && res.getData().size() > 0) {
                                scoreRule=res.getData().get(0).getExplain();
                            }
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
        APIRetrofit.getDefault().getUserInfo(Global.HEADER, "1")
                .compose(RxUtil.<BaseResult2<List<Doctor>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Doctor>>>() {
                    @Override
                    public void accept(BaseResult2<List<Doctor>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            List<Doctor> doctorList = result2.getData();
                            if (!isDataEmpty(doctorList)) {
                                tvTotalScore.setText(doctorList.get(0).getScore());
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
        showProgress();
    }
    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        reqDataList();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        scoreList.clear();
        adapter.notifyDataSetChanged();
        vRefresh.setEnableLoadMore(true);
        onLoadMore(vRefresh);
    }
    private Disposable reqDataList() {
        return APIRetrofit.getDefault().reqUserScore(Global.HEADER,mPage, mPageSize)
                .compose(RxUtil.<BaseResult2<List<Score>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Score>>>() {
                    @Override
                    public void accept(BaseResult2<List<Score>> result2) throws Exception {
                        hideProgress();
                        vRefresh.finishRefresh();
                        vRefresh.finishLoadMore();
                        if (result2.isSuccess()) {
                            mPage++;
                            scoreList.addAll(result2.getData());
//                            adapter.notifyDataSetChanged();
                            adapter.setDataList(scoreList);
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
//                        scoreList = result2.getData();
//                        adapter.setDataList(scoreList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private class MyScoreListAdapter extends ListBaseAdapter<Score> {

        public MyScoreListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_my_score_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            RelativeLayout rl_item = holder.getView(R.id.rl_item);
            TextView tv_title = holder.getView(R.id.tv_title);
            TextView tv_num = holder.getView(R.id.tv_num);
            TextView tv_time = holder.getView(R.id.tv_time);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) rl_item.getLayoutParams();
            if (position == 0) {
                params.topMargin = SizeUtils.dp2px(32);
                params.bottomMargin = SizeUtils.dp2px(16);
            } else if (position == mDataList.size() - 1) {
                params.topMargin = SizeUtils.dp2px(16);
                params.bottomMargin = SizeUtils.dp2px(32);
            } else {
                params.topMargin = SizeUtils.dp2px(16);
                params.bottomMargin = SizeUtils.dp2px(16);
            }

            Score score = mDataList.get(position);
            String title = score.getOrder_num() + PeUtil.getScoreStatus(score.getType());
            tv_title.setText(title);// // 积分来源 0 订单付款 1 退款 2 商城下单 3 商城取消支付
            String num = (TextUtils.equals("0", score.getStatus()) ? "＋" : "－") + score.getScore();
            tv_num.setText(num);
        }
    }
}